<?php


class ArticleMetaTag extends ArticleMeta
{
    public $keyName = 'tag';

    public function getTagsByArticle($aid, $isString=false)
    {
        $result = ArticleMeta::model()->findAll(' `key`=:key AND aid=:aid ',array(':key'=>$this->keyName,':aid'=>$aid));
        $resultTemp = array();
        foreach ($result as $key=>$value){
            $resultTemp[]=$value;
        }
        $result = $resultTemp;
        if( $result === null ){
            if( $isString ){
                return '';
            }else{
                return [];
            }
        }
        $result = array_column($result, 'value');
        if( $isString ){
            return implode(',', $result);
        }
        return $result;
    }

    public function setArticleTags($aid, $tags)
    {
        if( is_string($tags) ){
            if( empty($tags) ){
                $tags = [];
            }else {
                $tags = str_replace('，', ',', $tags);
                $tags = explode(',', $tags);
            }
        }
        $oldTags = $this->getTagsByArticle($aid);

        $needAdds = array_diff($tags, $oldTags);
        $needRemoves = array_diff($oldTags, $tags);

        foreach ($needAdds as $tag){
            $metaModel = new ArticleMeta();
            $metaModel->aid = $aid;
            $metaModel->key = $this->keyName;
            $metaModel->value = $tag;
            $metaModel->created_at = time();
            $metaModel->save();
        }

        foreach ($needRemoves as $tag){
            self::model()->find('`key`=:key AND value=:value AND aid=:aid',array(':key'=>$this->keyName,':value'=>$tag,':aid'=>$aid))->delete();
        }
    }

    public function getHotestTags($limit=12)
    {
        $model = new self();
        $tags = $model->findBySql("select value,COUNT(value) as times from {$model->tableName()} where `key`='{$this->keyName}' GROUP BY value order by times desc limit {$limit}")->asArray()->all();
        return array_map($tags, 'value', 'times');
    }

    public function getAidsByTag($tag)
    {
        $result = self::model()->findAll('`key`=:key AND value=:value',array(':key'=>$this->keyName,':value'=>$tag));
        $result = new ArrayObject($result); //将对象转为数组
        if( $result === null ) return [];
        return array_column($result, 'aid');
    }

}